<template>
  <div class="dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card online-clients">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-title">在线客户端</div>
              <div class="stats-number">{{ onlineClientsCount }}</div>
            </div>
            <div class="stats-icon">
              <el-icon><Monitor /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card total-clients">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-title">总客户端</div>
              <div class="stats-number">{{ totalClients }}</div>
            </div>
            <div class="stats-icon">
              <el-icon><Collection /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card system-uptime">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-title">系统运行时间</div>
              <div class="stats-number">{{ formatUptime(systemStats.system_uptime) }}</div>
            </div>
            <div class="stats-icon">
              <el-icon><Clock /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stats-card system-status">
          <div class="stats-content">
            <div class="stats-info">
              <div class="stats-title">系统状态</div>
              <div class="stats-number">正常</div>
            </div>
            <div class="stats-icon">
              <el-icon><CircleCheck /></el-icon>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 实时预警看板 -->
    <el-card class="alert-board-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><Warning /></el-icon>
            实时预警看板
          </span>
          <div class="card-actions">
            <el-button type="primary" size="small" @click="refreshAlerts">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button type="success" size="small" @click="viewAllAlerts">
              <el-icon><View /></el-icon>
              查看全部
            </el-button>
          </div>
        </div>
      </template>

      <!-- 预警筛选器 -->


      <div class="alert-list">
        <div v-if="filteredAlerts.length === 0" class="no-alerts">
          <el-icon class="no-alerts-icon"><CircleCheck /></el-icon>
          <span>暂无预警信息</span>
        </div>
        <div v-else class="alerts-scroll">
          <div
            v-for="alert in filteredAlerts"
            :key="alert.id"
            class="alert-item"
            :class="getAlertClass(alert.severity)"
          >
            <div class="alert-time-info">
              <div class="alert-time">{{ alert.time }}</div>
              <div class="alert-client-id">{{ alert.clientName }}</div>
            </div>
            <div class="alert-content">
              <span class="alert-message">{{ alert.message }}</span>
            </div>
            <el-tag :type="getAlertTagType(alert.severity)" size="small">
              {{ getAlertSeverityName(alert.severity) }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-card>



    <!-- 设备状态分布 -->
    <el-card class="device-status-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <el-icon><DataAnalysis /></el-icon>
            设备状态分布
          </span>
        </div>
      </template>

      <div class="device-status-grid">
        <div class="status-item online">
          <div class="status-count">{{ onlineClientsCount }}</div>
          <div class="status-label">在线设备</div>
          <div class="status-percentage">{{ getStatusPercentage('online') }}%</div>
        </div>
        <div class="status-item offline">
          <div class="status-count">{{ offlineClientsCount }}</div>
          <div class="status-label">离线设备</div>
          <div class="status-percentage">{{ getStatusPercentage('offline') }}%</div>
        </div>
        <div class="status-item warning">
          <div class="status-count">{{ warningClientsCount }}</div>
          <div class="status-label">预警设备</div>
          <div class="status-percentage">{{ getStatusPercentage('warning') }}%</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed, ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  Monitor, Collection, Clock, CircleCheck, Warning, View,
  Refresh, DataAnalysis
} from '@element-plus/icons-vue'
import { dashboardService, clientsService, usersService, departmentsService } from '@/services/dataService.js'
import { getAlertTypeName, getAlertTypeColor } from '@/config/app.js'

const router = useRouter()



const recentAlerts = ref([])
const loading = ref(false)
const clients = ref([])
const systemStats = ref({
  online_clients: 0,
  total_clients: 0,
  warning_clients: 0,
  system_uptime: 0
})

// 用户和部门数据
const availableUsers = ref([])
const availableDepts = ref([])


// 预警筛选器
const alertFilters = reactive({
  department: '',
  clientId: ''
})

// 计算属性
const onlineClients = computed(() => clients.value.filter(c => c.status === 'online'))
const totalClients = computed(() => systemStats.value.total_clients || clients.value.length)
const onlineClientsCount = computed(() => systemStats.value.online_clients || onlineClients.value.length)
const offlineClientsCount = computed(() => totalClients.value - onlineClientsCount.value)
const warningClientsCount = computed(() => systemStats.value.warning_clients || 0)



// 筛选后的预警列表
const filteredAlerts = computed(() => {
  return recentAlerts.value.filter(alert => {
    let matchDept = true
    let matchClient = true

    if (alertFilters.department) {
      matchDept = alert.department === alertFilters.department
    }

    if (alertFilters.clientId) {
      matchClient = alert.clientId === alertFilters.clientId
    }

    return matchDept && matchClient
  })
})

// 预警相关方法
const getAlertClass = (severity) => {
  const classMap = {
    1: 'alert-low',
    2: 'alert-medium',
    3: 'alert-high',
    4: 'alert-urgent',
    5: 'alert-critical'
  }
  return classMap[severity] || 'alert-low'
}

const getAlertTagType = (severity) => {
  const typeMap = {
    1: 'info',
    2: 'primary',
    3: 'warning',
    4: 'danger',
    5: 'danger'
  }
  return typeMap[severity] || 'info'
}

const getAlertSeverityName = (severity) => {
  const nameMap = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急',
    5: '严重'
  }
  return nameMap[severity] || '未知'
}

const getStatusPercentage = (status) => {
  const total = totalClients.value
  if (total === 0) return 0

  let count = 0
  switch (status) {
    case 'online':
      count = onlineClientsCount.value
      break
    case 'offline':
      count = offlineClientsCount.value
      break
    case 'warning':
      count = warningClientsCount.value
      break
  }

  return Math.round((count / total) * 100)
}

// 格式化时间函数 - 将ISO 8601格式转换为 YYYY/MM/DD HH:mm:ss 格式
const formatAlertTime = (timeString) => {
  try {
    const date = new Date(timeString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
  } catch (error) {
    console.error('时间格式化失败:', error)
    return timeString
  }
}

const refreshAlerts = async () => {
  try {
    loading.value = true
    const response = await dashboardService.getRecentAlerts({ limit: 10 })

    if (response.success || response.code === 200) {
      // 处理不同的响应格式
      const alertsData = response.data?.list || response.data || []

      // 转换API数据格式为组件需要的格式
      recentAlerts.value = alertsData.map(alert => ({
        id: alert.id,
        time: formatAlertTime(alert.created_at),
        clientName: alert.client_name || `客户端-${alert.client_id}`,
        message: alert.description,
        severity: alert.severity,
        department: alert.department || 'unknown',
        clientId: alert.client_id
      }))
      ElMessage.success('预警信息已刷新')
    }
  } catch (error) {
    console.error('获取预警数据失败:', error)
    ElMessage.error('获取预警数据失败')
  } finally {
    loading.value = false
  }
}

const viewAllAlerts = () => {
  router.push('/alert/list')
}

// 格式化运行时间
const formatUptime = (seconds) => {
  if (!seconds) return '00:00:00'

  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 加载仪表板数据
const loadDashboardData = async () => {
  try {
    loading.value = true

    // 并行加载数据
    const [statsResponse, clientsResponse] = await Promise.all([
      dashboardService.getStats(),
      clientsService.getClients()
    ])

    if (statsResponse.success) {
      systemStats.value = statsResponse.data
    }

    if (clientsResponse.success) {
      clients.value = clientsResponse.data.list || clientsResponse.data
    }

  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    ElMessage.error('加载仪表板数据失败')
  } finally {
    loading.value = false
  }
}


// 加载用户数据
const loadUsers = async () => {
  try {
    const response = await usersService.getUsers({ size: 100 })
    if (response.success) {
      availableUsers.value = response.data.list || response.data
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 加载部门数据
const loadDepartments = async () => {
  try {
    const response = await departmentsService.getDepartmentOptions()
    if (response.success) {
      availableDepts.value = response.data
    }
  } catch (error) {
    console.error('加载部门数据失败:', error)
  }
}

// 定时器变量
let uptimeTimer = null
let alertTimer = null

// 生命周期
onMounted(async () => {
  // 加载基础数据
  await Promise.all([
    loadDashboardData(),
    loadUsers(),
    loadDepartments()
  ])

  // 加载预警数据
  await refreshAlerts()



  // 启动系统运行时间计时器
  uptimeTimer = setInterval(() => {
    if (systemStats.value.system_uptime) {
      systemStats.value.system_uptime += 1
    }
  }, 1000)

  // 定时刷新预警数据
  alertTimer = setInterval(() => {
    refreshAlerts()
  }, 30000) // 每30秒刷新一次预警
})

onUnmounted(() => {
  if (uptimeTimer) {
    clearInterval(uptimeTimer)
  }
  if (alertTimer) {
    clearInterval(alertTimer)
  }
})
</script>

<style scoped>
.dashboard {
  max-width: 1400px;
  margin: 0 auto;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  margin-bottom: 20px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-info {
  flex: 1;
}

.stats-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.stats-icon {
  font-size: 48px;
  opacity: 0.8;
}

/* 不同卡片的主题色 */
.online-clients .stats-icon {
  color: #409EFF;
}

.total-clients .stats-icon {
  color: #67C23A;
}

.system-uptime .stats-icon {
  color: #E6A23C;
}

.system-status .stats-icon {
  color: #67C23A;
}

.alert-board-card {
  margin-top: 20px;
}



.device-status-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.card-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}



.alert-list {
  min-height: 200px;
}

.no-alerts {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #67C23A;
}

.no-alerts-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.alerts-scroll {
  max-height: 300px;
  overflow-y: auto;
}

.alert-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.alert-item:hover {
  background-color: #f8f9fa;
}

.alert-item:last-child {
  border-bottom: none;
}

.alert-time-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 160px;
}

.alert-time {
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #303133;
  font-weight: 600;
}

.alert-client-id {
  font-size: 11px;
  color: #409EFF;
  font-weight: 500;
}

.alert-content {
  flex: 1;
  font-size: 14px;
}

.alert-message {
  color: #303133;
  line-height: 1.4;
}








/* 设备状态分布样式 */
.device-status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.status-item {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.status-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.status-item.online {
  background: linear-gradient(135deg, #67C23A, #85CE61);
  color: white;
}

.status-item.offline {
  background: linear-gradient(135deg, #F56C6C, #F78989);
  color: white;
}

.status-item.warning {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
  color: white;
}

.status-count {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.status-label {
  font-size: 14px;
  margin-bottom: 4px;
  opacity: 0.9;
}

.status-percentage {
  font-size: 12px;
  opacity: 0.8;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .card-actions {
    width: 100%;
    justify-content: flex-start;
  }

  .stats-number {
    font-size: 24px;
  }

  .stats-icon {
    font-size: 36px;
  }
}
</style>
